import {
  Client,
  Message
} from "paho-wxapp";
import { callbackify } from "util";

var client = null;
var cid = null;
var subtpoic = "/dev/status/"
var pubtopic = "/dev/control/"

const randomString = (len) => {
  len = len || 32;
  var $chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
  var maxPos = $chars.length;
  var pwd = "";
  for (let i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}

const connect = (callback) => {
  if (client && client.isConnected()) {
    subscribe(subtpoic + cid);
    return;
  }
  client = new Client(
    "wss://www.easywork.net.cn/mqtt",
    "weapp:" + randomString(5)
  );

  client.connect({
    userName: "微信小程序",
    password: "passwd2",
    useSSL: true,
    cleanSession: true,
    keepAliveInterval: 60,
    onSuccess: function(){
        wx.showToast({
          title: "连接成功"
        });
        subscribe(subtpoic + cid);
        client.onConnectionLost = function (responseObject) {
          console.log("onConnectionLost:" + responseObject.errorMessage);
        };
        client.onMessageArrived = function (msg) {
          callback(msg)
        };
    }
  });
}

const subscribe = (topic) => {
  topic = topic || subtpoic + cid;
  client.subscribe(topic, {
    qos: 2,
    onSuccess: function () {
      console.log(`订阅主题：${topic}`);
    }
  });
}

const unsubscribe = (topic) => {
  topic = topic || subtpoic + cid;
  client.unsubscribe(topic);
  console.log(`unsubscribe(${topic})`)
}

const publishMessage = (msg) => {
  if (!(client && client.isConnected())) {
    wx.showToast({
      title: "请先连接设备"
    });
    return;
  }
  var message = new Message(msg);
  message.destinationName = pubtopic + cid;
  client.send(message);
  console.log(message.destinationName + msg);
}

const setcid=(id)=>{
  cid=id
}

const getcid = () => {
  return cid
}

export {
  setcid,
  getcid,
  connect,
  subscribe,
  unsubscribe,
  publishMessage
}
